#!/bin/bash

RUN_TYPE=$1
PID=`jps -l | grep 'io.seata.server.Server' | awk '{print $1}'`

UPLOAD_CONFIG_SHELL=./upload-seata-config.sh
NACOS_HOST=proxy.ocsmk.com
NACOS_PORT=30036
NACOS_CONFIG_NAMESPACE=supreme-server
NACOS_CONFIG_GROUP=SEATA_GROUP

SEATA_HOST=proxy.ocsmk.com
SEATA_PORT=30037

if [ -z "$RUN_TYPE" ];
then
    echo "ERROR only one params at least [ config | start | stop | status ]"
    exit 1
elif [ "$RUN_TYPE" == "config" ];
then
    RUN_CMD="sh ${UPLOAD_CONFIG_SHELL} \
                -h $NACOS_HOST \
                -p $NACOS_PORT \
                -g $NACOS_CONFIG_GROUP \
                -t $NACOS_CONFIG_NAMESPACE \
                -u nacos \
                -w nacos"
    $RUN_CMD
elif [ "$RUN_TYPE" == "start" ];
then
    if [ -n "$PID" ] ; then
        echo "ERROR The SeataServer(${PID}) already running."
        exit 1;
    fi
#    RUN_CMD=nohup ./bin/seata-server.sh > start.out 2>&1 &
    RUN_CMD=nohup ./bin/seata-server.sh -p ${SEATA_PORT} -h ${SEATA_HOST} -m file > start.out 2>&1 &
    $RUN_CMD
    echo "The SeataServer will starting..."
elif [ "$RUN_TYPE" == "stop" ];
then
    if [ -z "$PID" ] ; then
        echo "ERROR No SeataServer running."
        exit 1;
    fi
    echo "The SeataServer(${PID}) is running..."
    RUN_CMD="kill ${PID}"
    $RUN_CMD
    echo "Send shutdown request to SeataServer(${PID}) OK"
elif [ "$RUN_TYPE" == "status" ];
then
    if [ -z "$PID" ] ; then
        echo "No SeataServer running."
    else
        echo "The SeataServer('${PID}') already running."
    fi
else
     echo "ERROR Error unknown params"
     exit 1
fi
